package com.pai4j.ugc.service.moment;
import com.pai4j.common.constants.MomentConstants;
import com.pai4j.domain.vo.request.request.MomentSaveOrUpdateVO;
import com.pai4j.ugc.repository.dao.IMomentMediaDAO;
import com.pai4j.ugc.repository.entity.MomentMediaEntity;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class MomentMediaService {


    @Autowired
    private IMomentMediaDAO momentMediaDAO;


    /**
     * 保存动态媒体资源
     * @param momentId 动态ID
     * @param momentSaveOrUpdate 动态保存或更新的VO对象，包含图片和视频信息
     * @return 保存成功返回true
     */
    public boolean saveMomentMedia(Long momentId, MomentSaveOrUpdateVO momentSaveOrUpdate) {

        // 删除原有的媒体资源
        List<MomentMediaEntity> medias = momentMediaDAO.findAllByMomentId(momentId);
        if (CollectionUtils.isNotEmpty(medias)) {
            momentMediaDAO.deleteAll(medias);
        }

        // 重新构建媒体资源列表
        medias = new ArrayList<MomentMediaEntity>();

        // 处理图片资源
        if (momentSaveOrUpdate.includeImage()) {
            medias = momentSaveOrUpdate.getImages().stream().map(img -> {
                MomentMediaEntity momentMediaEntity = new MomentMediaEntity();
                momentMediaEntity.setMomentId(momentId);
                momentMediaEntity.setResource(img);
                momentMediaEntity.setType(MomentConstants.MediaType.IMAGE.getType());
                return momentMediaEntity;
            }).collect(Collectors.toList());
        }

        // 处理视频资源
        if (momentSaveOrUpdate.includeVideo()) {
            MomentMediaEntity momentMediaEntity = new MomentMediaEntity();
            momentMediaEntity.setMomentId(momentId);
            momentMediaEntity.setType(MomentConstants.MediaType.VIDEO.getType());
            momentMediaEntity.setResource(momentSaveOrUpdate.getVideo());
            medias.add(momentMediaEntity);
        }

        // 保存新的媒体资源
        momentMediaDAO.saveAll(medias);
        return true;
    }

    /**
     * 根据动态ID和类型查询媒体资源
     * @param momentId 动态ID
     * @param type 媒体类型
     * @return 媒体资源列表
     */
    public List<MomentMediaEntity> medias(Long momentId, int type) {

        return momentMediaDAO.findAllByMomentIdAndType(momentId, type);
    }



}
